﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Renci.SshNet;


namespace MeasNetClient
{
    public partial class FormMaintenance : Form
    {
        public FormMaintenance()
        {
            InitializeComponent();

            Dictionary<string, string> MaintCommandsList = new Dictionary<string, string>()
            {
                {"System Name", "uname -a"},
                {"System Uptime", "uptime"},
                {"System Time", "date"},
                {"Running processes", "top -n 1"},
                {"Kernel messages", "dmesg"},
                {"USB devices", "lsusb"},
                {"Measurement processes", "ps aux | grep rtl"},
                {"Check RTLSDR dongle", "rtl_test -t"},
                {"System restart", "sudo reboot"},
            };
            // Commands list
            comboBoxCommand.DataSource = new BindingSource(MaintCommandsList, null);
            comboBoxCommand.DisplayMember = "Key";
            comboBoxCommand.ValueMember = "Value";
            string command = Convert.ToString(comboBoxCommand.SelectedValue);
            // Station Connection Parameters
            comboBoxStation.DisplayMember = "Name";
            comboBoxStation.ValueMember = "Id";
            //
        }

        private void buttonExecute_Click(object sender, EventArgs e)
        {
            progressBarMaintenance.Style = ProgressBarStyle.Marquee;
            progressBarMaintenance.MarqueeAnimationSpeed = 30;
            // Get Connection parameters from Database
            int stIdValue = Convert.ToInt32(comboBoxStation.SelectedValue);
            stationTableAdapter.FillById(mNCdataDataSet.Station, stIdValue);
            var row = mNCdataDataSet.Station.FirstOrDefault();
            //
            //string host = row.Fqdn.Trim();
            //string port = Convert.ToString(row.Port).Trim();
            //string user = row.User.Trim();
            //string passwd = row.Password.Trim();
            //
            string cmd = Convert.ToString(comboBoxCommand.SelectedValue);
            if (textBoxCmdDebug.Text != "")
            {
                cmd = textBoxCmdDebug.Text;
            }

            Dictionary<string, string> sshConVar = new Dictionary<string, string>()
            {
                { "host", row.Fqdn.Trim()},
                { "port", Convert.ToString(row.Port).Trim()},
                { "username", row.User.Trim()},
                { "passwd", row.Password.Trim()},
                { "command", cmd}
            };
            backgroundWorkerMaint.RunWorkerAsync(sshConVar);
        }

        private void backgroundWorkerMaint_DoWork(object sender, DoWorkEventArgs e)
        {
            Dictionary<string, string> sshConVar = (Dictionary<string,string>)e.Argument;
            string host = sshConVar["host"];
            string username = sshConVar["username"];
            string port = sshConVar["port"];
            string passwd = sshConVar["passwd"];
            string command = sshConVar["command"];

            PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(host, Convert.ToInt32(port), username, passwd);
            connectionInfo.Timeout = TimeSpan.FromSeconds(20);
            using (var client = new SshClient(connectionInfo))
            {
                try
                {
                    client.Connect();
                    using (var streamshell = client.CreateShellStream("dumb", 80, 24, 800, 600, 4096))
                    {
                        var prompt = streamshell.Expect("$");
                        //Console.WriteLine("Got the prompt: " + prompt);
                        //var command = "/home/pi/startFM.sh " + modulation + " " + frequency + "M " + rfgain + " " + bandwidth + "k " + Convert.ToString(streamBw) + " " + Convert.ToString(streamBw / 1000);
                        streamshell.WriteLine(command);
                        // Now wait for the prompt ...
                        var recvData = streamshell.Expect("$");
                        //Console.Write(recvData);
                        //
                        Action show_response = () => richTextBoxResponse.Text = recvData;
                        richTextBoxResponse.Invoke(show_response);
                    }

                    //var console_text = client.RunCommand(command);
                    //var txtVal = console_text.Result;
                    //Action show_response = () => richTextBoxResponse.Text = txtVal;
                    //richTextBoxResponse.Invoke(show_response);
                    client.Disconnect();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Something went wrong!\n" + ex);
                }
            }
        }

        private void backgroundWorkerMaint_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBarMaintenance.Style = ProgressBarStyle.Continuous;
            progressBarMaintenance.MarqueeAnimationSpeed = 0;
            MessageBox.Show("The task has been completed!");
        }

        private void FormMaintenance_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'mNCdataDataSet.Station' table. You can move, or remove it, as needed.
            this.stationTableAdapter.Fill(this.mNCdataDataSet.Station);
        }

        private void buttonRefreshStations_Click(object sender, EventArgs e)
        {
            this.stationTableAdapter.Fill(this.mNCdataDataSet.Station);
        }

        private void labelMaintCmd_DoubleClick(object sender, MouseEventArgs e)
        {
           
                textBoxCmdDebug.Visible = true;
         
        }
    }
}
